<template>
	<view class="preview" v-if="currentImg">
		<swiper circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(item, index) in classList" :key="item._id">
				<image v-if="readImgs.includes(index)" @click="maskChange" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		
		<view class="mask" v-if="maskState">
			<view class="goBack" @click="goBack" :style="{top:getStatusBarHeight()+'px'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>

			</view>
			<view class="count">{{currentIndex+1}} / {{classList.length}}</view>
			<view class="time"><uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat></view>
			<view class="date"><uni-dateformat :date="Date.now()" format="MM月dd日"></uni-dateformat></view>
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box"  @click="clickRate">
					<uni-icons type="star" size="23"></uni-icons>
					<view class="text">{{currentImg.score}}分</view>
				</view>
				<view class="box" @click="clickDownLoad">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		
		<uni-popup ref="infoPopup" type="bottom">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="clickInfoClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<text class="value" selectable>{{currentImg._id}}</text>
						</view>
<!-- 						<view class="row">
							<view class="label">分类：</view>
							<text class="value class">可爱萌宠</text>
						</view> -->
						<view class="row">
							<view class="label">评分：</view>
							<view class="value roteBox">
								<uni-rate readonly touchable="false" allowHalf :value="currentImg.score"/>
								<text class="score">{{currentImg.score}}分</text>
							</view>
						</view>
						<view class="row">
							<view class="label">摘要：</view>
							<text class="value" >{{currentImg.description}}
							</text>
						</view>
						<view class="row">
							<view class="label">标签：</view>
							<view class="value tags">
								<view class="tag" v-for="item in currentImg.tabs" :key="item">{{item}}</view>
							</view>
						</view>
						
						<view class="copyright">
							声明：本图片来自用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
						</view>
					</view>
				</scroll-view>
				
				<view class="footer">
					
				</view>
			</view>
		</uni-popup>
		
		<uni-popup ref="ratePopup" type="center" :is-mask-click="false">
			<view class="ratePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{isScored ? "评分过啦~" : "壁纸评分"}}</view>
					<view class="close" @click="clickRateClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<view class="rateBox">
					<uni-rate :disabled="isScored" 
						touchable 
						allowHalf 
						v-model="userScore"
						disabled-color="#FFCA3E"
						/>
					<text class="score">{{userScore}}分</text>
				</view>
				<view class="footer">
					<button class="btn" @click="submitScore" :disabled="!userScore || isScored" type="default" size="mini" plain>确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import {getStatusBarHeight} from '@/utils/system.ts';
	import {onLoad,onShareAppMessage,onShareTimeline} from '@dcloudio/uni-app'
	import {apiGetSetupScore, apiWriteDownLoad} from '@/api/api.js'
	
	// 分享给好友
	onShareAppMessage(()=>{
		return {
			title: "俏猪八壁纸-" + pageName,
			path: "pages/classlist/classlist?id=" + queryParams.classid +"&name=" + pageName
		}
	})
	
	// 分享到朋友圈
	onShareTimeline(()=>{
		return {
			title: "俏猪八壁纸-" + pageName,
			query: "id=" + queryParams.classid +"&name=" + pageName
			
			// 不设置 imageUrl 时，默认是 logo 图片
			// imageUrl: ""
		}
	})
	
	const maskState = ref(true)
	const infoPopup = ref(null);
	const ratePopup = ref(null);
	const userScore = ref(0);
	// 缓存数据
	const classList = ref([]);
	// 当前图片 _id
	const currentId = ref(null);
	// 当前图像信息
	const currentImg = ref();
	// 当前图片在分类列表数据数组中的下标
	const currentIndex = ref(0);
	// 带宽优化，仅加载当前图片、前一张图片、后一张图片  (存图片索引)
	const readImgs = ref([])
	// 判断是否已经评分, 默认false
	const isScored = ref(false)


	
	function readImgsFunc() {
		readImgs.value.push(
			currentIndex.value < 0 ? classList.value.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1
		)
		
		// 图片索引去重
		readImgs.value = [...new Set(readImgs.value)];
	}
	
	// swiper 滑动事件
	const swiperChange = (e)=>{
		currentIndex.value = e.detail.current;
		// 当前图片
		currentImg.value = classList.value[currentIndex.value];
		// 添加图片索引到 readImgs
		readImgsFunc();
	}

	// 取出 classlist.vue 传递过来的 item._id （当前点击图片的 _id）
	onLoad((e) => {
		currentId.value = e.id;
		currentIndex.value = classList.value.findIndex(item => item._id === e.id);
		// 当前图片
		currentImg.value = classList.value[currentIndex.value];
		// 添加图片索引到 readImgs
		readImgsFunc();
		console.log(currentImg.value);
	})
	
	// 使用缓存中的分类列表数据
	const storageClassList = uni.getStorageSync("storageClassList") || [];
	classList.value = storageClassList.map( item =>{
		return {
			...item,
			picurl: item.smallPicurl.replace("_small.webp", ".jpg")
		}
	})
	
	
	// 确认评分
	const submitScore = async ()=>{
		uni.showToast({
			title: "加载中..."
		});
		
		let {
			classid,
			_id:wallId
		} = currentImg.value;
		
		let res = await apiGetSetupScore({
			classid,
			wallId,
			userScore: userScore.value
		});
		uni.hideLoading();
		if (res.errCode === 0) {
			uni.showToast({
				title: "评分成功",
				icon: "none"
			});
			classList.value[currentIndex.value].userScore = userScore.value;
			// 更新storage缓存
			uni.setStorageSync("storageClassList", classList.value);
			clickRateClose();
		}
	}
	
	// 打开评分窗口
	const clickRate = ()=>{
		if (currentImg.value.userScore) {
			isScored.value = true;
			userScore.value = currentImg.value.userScore;
		} 
		ratePopup.value.open();	
	}
	// 关闭评分窗口
	const clickRateClose=()=>{
		ratePopup.value.close();
		// 重置评分标志位
		userScore.value = 0;
		isScored.value = false;
	}
	
	// 弹出信息弹窗
	const clickInfo = ()=>{
		console.log("信息");
		infoPopup.value.open();
	}
	
	// 关闭信息弹窗
	const clickInfoClose = ()=>{
		infoPopup.value.close();
	}
	

	// 遮罩状态
	const maskChange = ()=>{
		maskState.value = !maskState.value
	}
	
	// 返回按钮点击
	const goBack = ()=>{
		uni.navigateBack();
	}
	
	
	
	// 下载壁纸
	const clickDownLoad = async ()=> {
		// #ifdef H5
			uni.showToast({
				title: "请长按保存壁纸",
				icon: 'none'
			})
		// #endif
		
		// 如果不是 H5
		// #ifndef H5
		// 加载框
		uni.showLoading({
			title: "下载中",
			mask: true
		})
		
		try {
			// 记录下载信息接口
			let {classid, _id:wallId} = currentImg.value;
			let res = await apiWriteDownLoad({
				classid,
				wallId
			});
			if (res.errCode != 0) {
				throw err;
			}
			
			// 保存图片
			uni.getImageInfo({
				src: currentImg.value.picurl,
				success: (res) => {
					// 图片临时路径
					let path = res.path;
					uni.saveImageToPhotosAlbum({
						filePath:path,
						success(res) {
							uni.hideLoading();
							uni.showToast({
								title: '保存成功，可去相册查看',
								icon: 'none',
								duration: 2000
							})
						},
						fail(err) {
							uni.hideLoading();
							if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '保存失败，请重新点击下载',
									icon: 'none'
								});
								return;
							}
							
							uni.showModal({
								title:'提示',
								content: '需要您授权保存相册',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success(settingdata) {
												if (settingdata.authSetting['scope.writePhotosAlbum']) {
													uni.showToast({
														title: '获取权限成功',
														icon: 'none'
													})
												} else {
													uni.showToast({
														title:'获取权限失败',
														icon: 'none'
													})
												}
											}
										})
									}
								}
							})
						},
						complete(err) {
							// do nothing
							uni.hideLoading();
						}
					})
				}
			})
		} catch (err) {
			console.log(err);
			uni.hideLoading();
		}
		
		// #endif
	}
</script>

<style lang="scss" scoped>
.preview { 
	position: relative;
	swiper {
		height: 100vh;
		width: 100%;
		swiper-item {
			height: 100%;
			width: 100%;
			image {
				height: 100%;
				width: 100%;
			}
		}
	}
	.mask {
		/*提取公共样式：mask 紧邻的view*/
		&>view {
			position: absolute;
			left: 50%;
			transform: translate(-50%, 0);
			width: fit-content;
			color: #fff;
		}
		
		.goBack{
			width: 70rpx;
			height: 70rpx;
			background: rgba(0, 0, 0, 0.5);
			left: 0;
			transform: translate(20%, 0);
			margin-left: 0;
			border-radius: 100%;
			backdrop-filter: blur(10rpx);
			border: 1px solid rgba(255, 255, 255, 0.3);
			
			display: flex;
			justify-content: center;
			align-items: center;
		}
		
		.count {
			top: 10vh;
			padding: 8rpx 28rpx;
			border-radius: 50rpx;
			font-size: 28rpx;
			background: rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(10rpx);
		}
		.time {
			top: calc(10vh + 80rpx);
			font-size: 140rpx;
			font-weight: 100;
			text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			line-height: 1em;
		}
		.date {
			top: calc(10vh + 230rpx);
			font-size: 34rpx;
			line-height: 1em;
			text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
		}
		.footer {
			background: rgba(255, 255, 255, 0.8);
			bottom: 10vh;
			width: 65vw;
			height: 120rpx;
			border-radius: 120rpx;
			display: flex;
			justify-content: space-around;
			color: #000;
			
		    box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(20rpx);
			.box {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 0 12rpx;
				.text {
					font-size: 26rpx;
					
					color: $text-font-color-2;
				}
			}
			
			
		}
	}
	.infoPopup {
		width: 100vw;
		background-color: #fff;
		padding: 50rpx 30rpx;
		border-radius: 30rpx 30rpx 0 0 ;
		overflow: hidden;
		
		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;
			.title {
				color: $text-font-color-2;
				font-size: 28rpx;	
			}
			.close {
				padding: 10rpx;
			}
		}
		scroll-view{
			max-height: 54vh;
			.content{
				.row {
					display: flex;
					padding:  16rpx 0;
					align-items: center;
					font-size: 32rpx;
					line-height: 1.7em;
					.label {
						color: $text-font-color-3;
						width: 140rpx;
						text-align: center;
						font-size: 30rpx;
					}
					.value {
						flex: 1;
						/*兼容性写法，内容太多时防止挤压label空间*/
						width: 0;
					}
					.roteBox {
						display: flex;
						align-items: center;
						.score {
							padding-left: 20rpx;
							font-size: 26rpx;
							color: $text-font-color-2;
						}
					}
					.tags {
						display: flex;
						flex-wrap: wrap;
						align-items: center;
						.tag{
							border: 1px  solid $brand-theme-color;
							color: $brand-theme-color;
							font-size: 22rpx;
							padding: 10rpx 30rpx;
							line-height: 22rpx;
							margin: 10rpx 10rpx 10rpx 0rpx;
							border-radius: 40rpx;
							width: fit-content;
						}
					}
					.class {
						color: $brand-theme-color;
					}
				}
				.copyright {
					font-size: 28rpx;
					padding: 28rpx;
					background: #F6F6F6;
					color: #666;
					border-radius: 10rpx;
					margin: 20rpx 0;
					line-height: 1.6em;
				}
				
			}
		}
		.footer {
			
		}
	}
	.ratePopup{
		background-color: #fff;
		width: 70vw;
		height: 335rpx;	
		border-radius: 30rpx;
		box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.3);
		overflow: hidden;
		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: $text-font-color-3;
			padding: 45rpx 40rpx;
		}
		.rateBox{
			height: 90rpx;
			display: flex;
			align-items: center; 
			justify-content: center;
			.score {
				padding-left: 48rpx; 
				font-size: 30rpx;
				color: #f0c752;
				text-align: right;
			}
		}
		.footer {
			// height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			padding-top: 40rpx;
			
			// .btn {
			// 	align-items: center;
			// 	height: 60rpx;
			// 	line-height: 60rpx;
			// 	margin: 30rpx 0;
			// 	padding: 0 40rpx;
			// 	// font-size: 24rpx;
			// }
		}
	}
}


</style>
